package com.gopay.commons.validator;

import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 系统文件定位
 * 
 * @SystemValidatorDefine.java
 * @author yaobo
 * @2012-12-26 上午09:54:29 www.gopay.com.cn Inc.All rights reserved.
 */
public class SystemValidatorDefine implements ValidatorDefine {

    /**
     * 将多个XML文件合并为一个XML以Document返回
     * 
     * @param documents
     * @return
     * @throws DocumentException
     */
    @Override
    @SuppressWarnings("unchecked")
    public Document merge(Document[] documents) throws DocumentException {
        if (documents == null || documents.length == 0) {
            throw new DocumentException("merge fial the documents is null");
        }

        String form_xml = "<forms></forms>";
        Document newDocument = DocumentHelper.parseText(form_xml);
        String xpath = "/forms";
        Document document = null;
        Element element = null;
        for (int i = 0; i < documents.length; i++) {
            document = documents[i];
            if (document != null) {
                List<Element> elements = document.selectNodes(xpath);
                if (elements != null && elements.size() > 0) {
                    for (Iterator<Element> it = elements.iterator(); it.hasNext();) {
                        element = (Element) it.next();
                        newDocument.getRootElement().appendContent(element);
                    }
                }
            }
        }

        // 模板合规检查待完成
        ValidatorTemplateCheck.isValidatorCheck(newDocument);

        return newDocument;
    }

    /**
     * 将定位的formPath路径转成Document数组
     * 
     * @param formPath
     *            文件路径
     * @return
     * @throws DocumentException
     */
    @Override
    public Document[] read(List<String> formPath) throws DocumentException {

        if (formPath == null || formPath.size() == 0) {
            throw new DocumentException("no validator file.");
        }

        Document[] documents = new Document[formPath.size()];
        SAXReader reader = new SAXReader();
        Document document = null;
        String file = null;
        String filePath = null;
        int i = 0;

        for (Iterator<String> it = formPath.iterator(); it.hasNext();) {
            file = (String) it.next();

            filePath = getFilePath(file);
            document = reader.read(filePath);

            documents[i] = document;
            i++;
        }

        return documents;
    }

    private String getFilePath(String file) {
        String path = this.getClass().getResource("/").toString();
        String fullPath = path + file;
        return fullPath;
    }
}
